package com.wsc.controller;

import cn.hutool.json.JSONUtil;
import com.wsc.domain.Rule;
import com.wsc.service.IChatHistoryService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.ExtractedTextFormatter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/ai/service")
public class MobileController {
    @Autowired
    private IChatHistoryService chatHistoryService;
    @Autowired
    private ChatClient chatClient;
    @Autowired
    private VectorStore vectorStore;

    @RequestMapping(produces = "text/html;charset=utf-8")
    public Flux<String> chat(String prompt, String chatId) {
        chatHistoryService.saveChatHistory("mobile", chatId);
        String json = """
                [
                  {
                    "id": "rule_01",
                    "type": "合约期",
                    "condition": "合约期未满12个月",
                    "description": "提前更换套餐需支付剩余费用的10%作为违约金。"
                  },
                  {
                    "id": "rule_02",
                    "type": "携号转网",
                    "condition": "申请携号转网",
                    "description": "需满足：1. 无欠费 2. 当前套餐已到期 3. 非吉祥号段（如138/139开头）。"
                  }
                ]
                """;
        List<Rule> list = JSONUtil.toList(json, Rule.class);
        writeToVectorStore(list);

        return chatClient.prompt(prompt)
                //保存至自己的数据库中
                .advisors(advisorSpec -> advisorSpec.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream().content();
    }

    private void writeToVectorStore(List<Rule> rules) {
        List<Document> documents = rules.stream()
                .map(rule -> {
                    Map<String, Object> metadata = new HashMap<>();
                    metadata.put("type", rule.getType());
                    metadata.put("condition", rule.getCondition());
                    metadata.put("id", rule.getId());
                    metadata.put("description", rule.getDescription());

                    // 明确在内容中包含规则ID
                    String content = "规则ID: " + rule.getId() + " " + rule.getDescription();
                    return new Document(rule.getId(), content, metadata);
                })
                .collect(Collectors.toList());

        vectorStore.add(documents);
    }

}
